package com.work.formaldehyde.activity;

import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.work.formaldehyde.R;
import com.work.formaldehyde.activityadapter.JianCeDateAdapter;
import com.work.formaldehyde.activityadapter.JianCeDatesAdapter;
import com.work.formaldehyde.activityadapter.JianCeJiLuAdapter;
import com.work.formaldehyde.activityadapter.JianCeJiLusAdapter;
import com.work.formaldehyde.model.JianCeDateModel;
import com.work.formaldehyde.orderfragment.DSHFragment;
import com.work.formaldehyde.orderfragment.DZFFragment;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.Url;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class JianCeJiLuActivity extends Activity implements View.OnClickListener {
    private ImageView comeback;
    private RelativeLayout add_check_text;
    private LinearLayout zhuwo, wendu, shidu, jiaquan, shijian;
    private TextView zhuwotext;
    private LinearLayout gettop;
    private ImageView zhuwojiantou, shijianjiantou;
    private ArrayList<JianCeDateModel.data> jcdmodel = new ArrayList<>();
    private ArrayList<String> jcdmodels = new ArrayList<>();
    private JianCeDateModel jianCeDateModel;


    private ArrayList<JianCeDateModel.data> zhuwoary = new ArrayList<>();
    private ArrayList<JianCeDateModel.data> ciwolist = new ArrayList<>();
    private ArrayList<JianCeDateModel.data> ketinglist = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ApiUtils.ActivityIsLogin(this, 1);
        setContentView(R.layout.activity_jiancejilu);
        comeback = findViewById(R.id.jiance_comeback);
        comeback.setOnClickListener(this);
        if (ApiUtils.isNetworkConnected(JianCeJiLuActivity.this))
            init();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


    private JianCeJiLuAdapter jianCeJiLuAdapter;
    private JianCeJiLusAdapter jianCeJiLusAdapter;
    private ArrayList<String> zhuwolist = new ArrayList<>();
    private ArrayList<String> zhuwolist1 = new ArrayList<>();
    private ArrayList<String> zhuwolists = new ArrayList<>();
    private ArrayList<String> zhuwolisttime = new ArrayList<>();
    private ArrayList<String> roomname = new ArrayList<>();
    private ListView jiancedate_list;
    private ArrayList<String> checktime = new ArrayList<>();

    public void Init() {
        for (int is = 0; is < 3; is++) {
            zhuwolist.add("1");
            if (is == 0) {
                zhuwolist1.add("主卧");
                checktime.add("2018年");
            }
            if (is == 1) {
                zhuwolist1.add("次卧");
                checktime.add("2019年");
            }
            if (is == 2) {
                zhuwolist1.add("客厅");
                checktime.add("2020年");
            }
        }
        jianCeJiLuAdapter = new JianCeJiLuAdapter(zhuwolist, zhuwolist1,
                JianCeJiLuActivity.this);
        jianCesAdapter = new JianCeDatesAdapter(checktime,
                JianCeJiLuActivity.this);
        jianCeJiLusAdapter = new JianCeJiLusAdapter(zhuwolisttime, zhuwolists,
                JianCeJiLuActivity.this);
        myAdapter = new JianCeDateAdapter(jcdmodel,
                JianCeJiLuActivity.this);
        jiancedate_list.setAdapter(myAdapter);
    }

    private String wendus, shidus, jiaquans;
    JianCeDatesAdapter jianCesAdapter;

    /**
     * 初始加载
     */
    public void init() {
        jiancedate_list = findViewById(R.id.jiancedate_list);
        gettop = findViewById(R.id.gettop);
        add_check_text = findViewById(R.id.add_check_text);
        add_check_text.setOnClickListener(this);
        zhuwo = findViewById(R.id.zhuwo);
        zhuwo.setOnClickListener(this);
        wendu = findViewById(R.id.wendu);
        wendu.setOnClickListener(this);
        shidu = findViewById(R.id.shidu);
        shidu.setOnClickListener(this);
        jiaquan = findViewById(R.id.jiaquan);
        jiaquan.setOnClickListener(this);
        shijian = findViewById(R.id.shijian);
        shijian.setOnClickListener(this);
        zhuwotext = findViewById(R.id.zhuwotext);
        zhuwojiantou = findViewById(R.id.zhuwojiantou);
        shijianjiantou = findViewById(R.id.shijianjiantou);
        Init();
        if (!Url.USER_ID.equals(""))
            okHttp_postFromParameters();
        else
            ApiUtils.SetToast(JianCeJiLuActivity.this, "请先登录");
        jiancedate_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (caozuo) {
                    recordid = jcdmodel.get(position).getId();
                    wendus = jcdmodel.get(position).getTemp();
                    shidus = jcdmodel.get(position).getHumidity();
                    jiaquans = jcdmodel.get(position).getHcho();
                    windows1(JianCeJiLuActivity.this, view);
                } else
                    ApiUtils.SetToast(JianCeJiLuActivity.this, "数据更新中");
            }
        });
    }

    public boolean caozuo = true;
    public static boolean isboole = false;

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!Url.USER_ID.equals("") && ApiUtils.isNetworkConnected(JianCeJiLuActivity.this) && isboole) {
            okHttp_postFromParameters();
            isboole = false;
        }
    }

    private Boolean kq = true, hw = true;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.jiance_comeback:
                onBackPressed();
                break;
            case R.id.add_check_text:
                Intent tojiance = new Intent(JianCeJiLuActivity.this, AddCeLiangActivity.class);
                tojiance.putExtra("zhuangtai", "0");
                tojiance.putExtra("wendu", "");
                tojiance.putExtra("shidu", "");
                tojiance.putExtra("jiaquan", "");
                tojiance.putExtra("id", "");
                startActivity(tojiance, ActivityOptions.makeSceneTransitionAnimation(JianCeJiLuActivity.this).toBundle());
                break;
            case R.id.zhuwo:
                zhuwojiantou.setPivotX(zhuwojiantou.getWidth() / 2);
                zhuwojiantou.setPivotY(zhuwojiantou.getHeight() / 2);
                if (kq) {
                    zhuwojiantou.animate().rotation(180);
                    kq = false;
                    windows(JianCeJiLuActivity.this, 0);
                }

                break;
            case R.id.shijian:
                shijianjiantou.setPivotX(shijianjiantou.getWidth() / 2);
                shijianjiantou.setPivotY(shijianjiantou.getHeight() / 2);
                if (hw) {
                    shijianjiantou.animate().rotation(180);
                    hw = false;
                    windows(JianCeJiLuActivity.this, 1);
                }
                break;
        }
    }

    private PopupWindow popupWindows;
    private String getroomname = "", getroomnames = "";

    public void windows(Context context, final int index) {
        View popupwindowviews = LayoutInflater.from(context).inflate(
                R.layout.popupwindow_zhuwo, null);
        final ListView zhuwo_check_list = popupwindowviews.findViewById(R.id.zhuwo_check_list);
        if (index == 0) {
            zhuwo_check_list.setAdapter(jianCeJiLuAdapter);
        } else {
            zhuwo_check_list.setAdapter(jianCeJiLusAdapter);
        }
        zhuwo_check_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (index == 0) {
                    if (zhuwolist.get(i).equals("2")) {
                        zhuwolist.set(i, "1");
                        getroomname = getroomname.replace(zhuwolist1.get(i), "");
                    } else {
                        zhuwolist.set(i, "2");
                        getroomname = getroomname + zhuwolist1.get(i);
                    }
                    jianCeJiLuAdapter.notifyDataSetChanged();
                } else {
                    if (zhuwolists.get(i).equals("2")) {
                        zhuwolists.set(i, "1");
                        getroomnames = getroomname.replace(zhuwolist1.get(i), "");
                    } else {
                        zhuwolists.set(i, "2");
                        getroomnames = getroomnames + zhuwolist1.get(i);
                    }
                    jianCeJiLusAdapter.notifyDataSetChanged();
                }
            }
        });
        popupWindows = new PopupWindow(popupwindowviews, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindows.setTouchable(true);
        popupWindows.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
                if (index == 0) {
                    zhuwojiantou.animate().rotation(360);
                    kq = true;
                } else {
                    shijianjiantou.animate().rotation(360);
                    hw = true;
                }
                if (getroomname.length() == 2) {
                    zhuwoary.clear();
                    for (int s = 0; s < jcdmodel.size(); s++) {
                        if (jcdmodel.get(s).getRoom().equals(getroomname)) {
                            zhuwoary.add(jianCeDateModel.getData().get(s));
                        }
                    }
                }
                if (getroomname.length() == 4) {
                    zhuwoary.clear();
                    for (int s = 0; s < jcdmodel.size(); s++) {
                        if (jcdmodel.get(s).getRoom().equals(getroomname.substring(0, 2))) {
                            zhuwoary.add(jianCeDateModel.getData().get(s));
                        }
                        if (jcdmodel.get(s).getRoom().equals(getroomname.substring(2, 4))) {
                            zhuwoary.add(jianCeDateModel.getData().get(s));
                        }
                    }
                }
                if (getroomname.length() == 6) {
                    zhuwoary.clear();
                    for (int s = 0; s < jcdmodel.size(); s++) {
                        if (jcdmodel.get(s).getRoom().equals(getroomname.substring(0, 2))) {
                            zhuwoary.add(jianCeDateModel.getData().get(s));
                        }
                        if (jcdmodel.get(s).getRoom().equals(getroomname.substring(2, 4))) {
                            zhuwoary.add(jianCeDateModel.getData().get(s));
                        }
                        if (jcdmodel.get(s).getRoom().equals(getroomname.substring(4, 6))) {
                            zhuwoary.add(jianCeDateModel.getData().get(s));
                        }
                    }
                }

                if (getroomnames.length() == 4) {
                    zhuwoary.clear();
                    String time = "";
                    for (int s = 0; s < jcdmodel.size(); s++) {
                        time = jcdmodel.get(s).getTimes();
                        if (time.substring(0, 4).equals(getroomnames)) {
                            zhuwoary.add(jianCeDateModel.getData().get(s));
                        }
                    }
                }
                if (getroomnames.length() == 8) {
                    zhuwoary.clear();
                    String time = "";
                    for (int s = 0; s < jcdmodel.size(); s++) {
                        time = jcdmodel.get(s).getTimes();
                        if (time.substring(0, 4).equals(getroomname.substring(0, 4))) {
                            zhuwoary.add(jianCeDateModel.getData().get(s));
                        }
                        if (time.substring(0, 4).equals(getroomname.substring(4, 8))) {
                            zhuwoary.add(jianCeDateModel.getData().get(s));
                        }
                    }
                }
                if (getroomnames.length() == 12) {
                    zhuwoary.clear();
                    String time = "";
                    for (int s = 0; s < jcdmodel.size(); s++) {
                        time = jcdmodel.get(s).getTimes();
                        if (time.substring(0, 4).equals(getroomnames.substring(0, 4))) {
                            zhuwoary.add(jianCeDateModel.getData().get(s));
                        }
                        if (time.substring(0, 4).equals(getroomnames.substring(4, 8))) {
                            zhuwoary.add(jianCeDateModel.getData().get(s));
                        }
                        if (time.substring(0, 4).equals(getroomnames.substring(8, 12))) {
                            zhuwoary.add(jianCeDateModel.getData().get(s));
                        }
                    }
                }
                JianCeDateAdapter myAdapter = new JianCeDateAdapter(jcdmodel,
                        JianCeJiLuActivity.this);
                jiancedate_list.setAdapter(myAdapter);
            }
        });
        popupWindows.setFocusable(true);
        popupWindows.setOutsideTouchable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);
        popupWindows.showAsDropDown(gettop, 0, 0);
    }

    private void okHttp_postFromParameters() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
//                    RequestBody formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("uid", Url.LOGIN_TOKEN)
//                            .build();
//                    Request request = new Request.Builder().url(Url.GETCELIANGS).post(formBody).build();
//                    okhttp3.Response response = okHttpClient.newCall(request).execute();
//                    String msg = response.body().string();
//                    Message message = new Message();
//                    message.obj = msg;
//                    gethot1.sendMessage(message);
                    Request request = new Request.Builder().get().url(Url.GETCELIANGS+"?uid=" + Url.USER_ID + "&logintoken=" + Url.LOGIN_TOKEN).build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onResponse(Call call, final Response response) {
                            try {
                                final String responseStr;
                                responseStr = response.body().string();
                                Message message = new Message();
                                message.obj = responseStr;
                                gethot1.sendMessage(message);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    JianCeDateAdapter myAdapter;

    public Handler gethot1 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        caozuo = true;
                        Gson gson = new Gson();
                        jianCeDateModel = gson.fromJson(msg.obj.toString(),
                                JianCeDateModel.class);
                        jcdmodel.clear();
                        jcdmodel.addAll(jianCeDateModel.getData());
                        for (int is = 0; is < jcdmodel.size(); is++) {
                            zhuwolisttime.add(jcdmodel.get(is).getTimes());
                            zhuwolists.add("1");
                        }
                        jianCeJiLusAdapter.notifyDataSetChanged();
                        myAdapter.notifyDataSetChanged();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    public void windows1(Context context, View v) {
        View popupwindowviews = null;
        popupwindowviews = LayoutInflater.from(context).inflate(
                R.layout.popup_isdels, null);
        RelativeLayout dangqian = popupwindowviews.findViewById(R.id.dangqian);
        dangqian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ApiUtils.windows(JianCeJiLuActivity.this, jiancedate_list, "删除中...");
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        ApiUtils.closepopup();
                    }
                }, 10000);
                okHttp_Del();
                popupWindows.dismiss();
            }
        });
        RelativeLayout update = popupwindowviews.findViewById(R.id.update);
        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent toxdw = new Intent(JianCeJiLuActivity.this, AddCeLiangActivity.class);
                toxdw.putExtra("zhuangtai", "1");
                toxdw.putExtra("wendu", wendus);
                toxdw.putExtra("shidu", shidus);
                toxdw.putExtra("jiaquan", jiaquans);
                toxdw.putExtra("id", recordid);
                startActivity(toxdw, ActivityOptions.makeSceneTransitionAnimation(JianCeJiLuActivity.this).toBundle());
                popupWindows.dismiss();
            }
        });
        RelativeLayout jieshu = popupwindowviews.findViewById(R.id.jieshu);
        jieshu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindows.dismiss();
            }
        });
        popupWindows = new PopupWindow(popupwindowviews, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindows.setAnimationStyle(R.style.popwin_anim_style);
        popupWindows.setTouchable(true);
        popupWindows.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        popupWindows.setFocusable(true);
        popupWindows.setOutsideTouchable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);
        popupWindows.showAtLocation(v, Gravity.BOTTOM, 0, 0);
    }

    public String recordid;

    private void okHttp_Del() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = null;
                    Request request;
                    formBody = new FormBody.Builder()
                            .add("uid", Url.USER_ID) .add("logintoken", Url.LOGIN_TOKEN).add("recordid", recordid).build();
                    request = new Request.Builder().url(Url.DELCELIANG).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    getdel.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public Handler getdel = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        caozuo = false;
                        okHttp_postFromParameters();
                        ApiUtils.SetToast(JianCeJiLuActivity.this, "操作成功");
                    } else {
                        ApiUtils.SetToast(JianCeJiLuActivity.this, "操作失败");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


}
